package com.qall.util;

import org.springframework.util.StringUtils;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class FileUtil {

    /**
     * 读文件
     *
     * @param path
     * @return
     */
    public static Map<String, String> readFile(String path) {
        File file = new File(path);
        try {
            FileReader fr = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(fr);
            Map<String, String> map = new HashMap<>();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                if (StringUtils.hasText(line)) {
                    String[] data = line.split(Constant.SPLIT);
                    map.put(data[0], data[1]);
                }
            }
            bufferedReader.close();
            return map;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 写文件
     *
     * @param message
     */
    public static void writeToFile(String message, String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        }
        try {
            Writer fr = new FileWriter(file);
            BufferedWriter bufferedWriter = new BufferedWriter(fr);
            bufferedWriter.write(message);
            bufferedWriter.close();
            fr.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
